<template>
    <el-drawer :title="title" v-model="show" size="35%">
        <template #default>
            <el-form ref="formRef" :rules="rules" :model="form" label-width="auto">
                <el-form-item label="商户号" prop="merId">
                    <el-input v-model.trim="form.merId" maxlength="30" show-word-limit placeholder="请输入商户号" />
                </el-form-item>
                <el-form-item label="API密钥" prop="paySign">
                    <el-input v-model.trim="form.paySign" placeholder="请输入API密钥" />
                </el-form-item>
                <el-form-item label="私钥文件" prop="cerPath" :error="uploadErrMsg.cerPath">
                    <FileUpload
                        :merId="form.merId"
                        @clear="fileClear($event, 'cer')"
                        :files="buildFormFile('cer')"
                        @fileStateChange="fileChangeHandler($event, 'cer')"></FileUpload>
                </el-form-item>
                <el-form-item label="公钥文件" prop="pfxPath" :error="uploadErrMsg.pfxPath">
                    <FileUpload
                        :merId="form.merId"
                        :files="buildFormFile('pfx')"
                        @clear="fileClear($event, 'pfx')"
                        @fileStateChange="fileChangeHandler($event, 'pfx')"></FileUpload>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div class="container-footer">
                <span class="tip"></span>
                <div style="flex: auto">
                    <el-button @click="closeHandler">取消</el-button>
                    <el-button type="primary" @click="submitHandler">提交</el-button>
                </div>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
import { ref, computed, reactive, inject, watch } from 'vue';
import request from '@/request';
import { isNotEmpty, cloneDeep } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import FileUpload from './upload.vue';

/** 通信bus */
const bus = inject('bus');

/** 弹框显示隐藏 */
const props = defineProps({
    modelValue: Boolean,
    title: { type: String, default: '' },
    store: { type: Object, default: () => {} }
});
const emit = defineEmits(['update:modelValue', 'submit']);
const show = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

/** form表单 */
const fzForm = {
    // 商户号
    merId: '',
    // api密钥
    paySign: '',
    // 私钥文件
    cerPath: '',
    cerName: '',
    // 公钥文件
    pfxPath: '',
    pfxName: ''
};
const formRef = ref(null);
let form = reactive(cloneDeep(fzForm));
const uploadErrMsg = reactive({
    cerPath: '',
    pfxPath: ''
});

// 监听store
watch(
    () => show,
    val => {
        if (val && props.store?.merId) {
            form = Object.assign(form, props.store);
        }
    },
    {
        deep: true
    }
);

/**
 * 表单验证
 */
const rules = reactive({
    merId: [{ required: true, message: '请输入商户号', trigger: 'blur' }],
    paySign: [{ required: true, message: '请输入API密钥', trigger: 'blur' }],
    cerPath: [{ required: true, message: '请上传私钥文件', trigger: 'blur' }],
    pfxPath: [{ required: true, message: '请上传公钥文件', trigger: 'blur' }]
});

/**
 * 关闭drawer
 */
const closeHandler = () => {
    show.value = false;
};

const buildFormFile = prop => {
    let arr = [];
    if (form[prop + 'Path']) {
        arr.push({
            name: form[prop + 'Name'] || form[prop + 'Path']?.split('/').pop(),
            url: form[prop + 'Path']
        });
    }
    return arr;
};

const fileChangeHandler = ({ fileUrl, fileName, msg }, prop) => {
    if (fileUrl !== undefined) {
        form[prop + 'Path'] = fileUrl || '';
        !msg && formRef.value.validateField(prop + 'Path');
    }
    if (fileName !== undefined) {
        form[prop + 'Name'] = fileName || '';
    }
    uploadErrMsg[prop] = msg || '';
};
const fileClear = (event, prop) => {
    form[prop + 'Path'] = '';
    form[prop + 'Name'] = '';
};

/**
 * 提交
 */
const submitHandler = () => {
    formRef.value.validate(async valid => {
        if (valid) {
            emit('submit', form);
            bus.on('paymp:update', closeHandler);
        }
    });
};
</script>
<style lang="scss" scoped>
.container-footer {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .tip {
        color: #555;
        font-weight: 500;
        font-size: 12px;
    }
}
</style>
